import { sendEmailCodeData } from './dto/sendEmailCode.dto'
import { BadRequestException, Body, Controller, Post } from '@nestjs/common'
import { emailService } from './email.service'
import dayjs from 'dayjs'

@Controller('email')
export class EmailController {
  constructor(private emailService: emailService) {}

  @Post('/sendCode')
  async sendEmailCode(@Body() Body: sendEmailCodeData) {
    // 查看是否发送过邮件或者邮件是否已经过期
    if (!(await this.emailService.ifCodeLimt(Body.email))) {
      throw new BadRequestException({ message: ['请等待1分钟后再次尝试'] })
    }
    // 发送验证码到邮箱
    // 拿到验证码和发送时间，存储数据库，方便登录校验
    const code = Math.random().toString().slice(-5)
    const date = dayjs().format('YYYY-MM-DD HH:mm:ss')
    try {
      this.emailService.sendEmailCode({
        code,
        subject: '您在nest_admin上获取的验证码',
        target: Body.email,
        date,
      })
    } catch (err) {
      console.log(err)
    }
    await this.emailService.storageCode({ email: Body.email, code, time: dayjs(date).toJSON() })
    return {
      message: '获取成功',
    }
  }
}
